package org.linlinjava.litemall.wx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LumiereCouponStrategy;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LumiereCouponStrategyService;
import org.linlinjava.litemall.wx.annotation.LogAnno;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.dto.UserRechargeDTO;
import org.linlinjava.litemall.wx.dto.WxResetPaymentCodeByCodeDTO;
import org.linlinjava.litemall.wx.service.WxUserService;
import org.linlinjava.litemall.wx.util.URLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.db.domain.LitemallCoupon.Column.code;

/**
 * wx用户控制器
 * 用户服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Api(tags = "用户API")
@RestController
@RequestMapping("/wx/user")
@Validated
public class WxUserController {
    /**
     * 日志记录器
     */
    private final Log logger = LogFactory.getLog(WxUserController.class);

    /**
     * PAYPAL成功url
     */
    @Value("${paypal.paypal_success_url}")
    public String PAYPAL_SUCCESS_URL;
    /**
     * PAYPAL取消url
     */
    @Value("${paypal.paypal_cancel_url}")
    public String PAYPAL_CANCEL_URL;

    /**
     * url工具
     */
    @Autowired
    private URLUtils urlUtils;

    /**
     * 订单服务
     */
    @Autowired
    private LitemallOrderService orderService;

    /**
     * wx用户服务
     */
    @Autowired
    private WxUserService wxUserService;


    @ApiOperation("用户-「支付密码校验」")
    @GetMapping("/verify")
    @ApiImplicitParam(name = "payCode",value = "支付密码")
    @LogAnno
    public Object verify(@ApiIgnore  @LoginUser Integer userId,
                         @RequestParam("payCode")Integer payCode){
        return wxUserService.verify(userId,payCode);
    }

    @ApiOperation("用户-「设置支付密码」")
    @GetMapping("/paymentCode")
    @ApiImplicitParam(name = "payCode",value = "支付密码")
    @LogAnno
    public Object paymentCode(@ApiIgnore  @LoginUser Integer userId,
                              @RequestParam("payCode")Integer payCode){
        return wxUserService.paymentCode(userId,payCode);
    }

    @ApiOperation("用户-「重置支付密码」")
    @GetMapping("/resetPaymentCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPayCode",value = "支付密码"),
            @ApiImplicitParam(name = "newPayCode",value = "支付密码")
    })
    @LogAnno
    public Object resetPaymentCode(@ApiIgnore  @LoginUser Integer userId,
                                   @RequestParam("oldPayCode")Integer oldPayCode,
                                   @RequestParam("newPayCode")Integer newPayCode){
        return wxUserService.resetPaymentCode(userId ,oldPayCode,newPayCode);
    }

    @ApiOperation("用户-「删除支付密码」")
    @GetMapping("/removePay")
    @LogAnno
    public Object removePay(@ApiIgnore @LoginUser Integer userId){
        return wxUserService.removePay(userId);
    }

    @ApiOperation("用户-「重置支付密码 手机号｜邮箱」")
    @PostMapping("/resetPaymentCodeByCode")
    @LogAnno
    public Object resetPaymentCodeByCode(@ApiIgnore @LoginUser Integer userId,
                                         @RequestBody WxResetPaymentCodeByCodeDTO resetPaymentCodeByCodeDTO){
        return wxUserService.resetPaymentCodeByCode(userId,resetPaymentCodeByCodeDTO);
    }



    /**
     * 用户个人页面数据
     * <p>
     * 目前是用户订单统计信息
     *
     * @param userId 用户ID
     * @return 用户个人页面数据
     */
    @GetMapping("index")
    @LogAnno
    public Object list(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("order", orderService.orderInfo(userId));
        return ResponseUtil.ok(data);
    }

    /**
     * 充电
     *
     * @param userId 用户id
     * @param dto    dto
     * @return {@link Object}
     */
    @PostMapping("recharge")
    @LogAnno
    public Object recharge(@LoginUser Integer userId, @RequestBody @Valid UserRechargeDTO dto) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok(wxUserService.recharge(userId, dto));
    }


    /**
     * 支付
     *
     * @param userId  用户id
     * @param id      id
     * @param res     res
     * @param request 请求
     * @return {@link Object}
     * @throws Exception 异常
     */
    @GetMapping("recharge")
    @LogAnno
    public Object pay(@LoginUser Integer userId, @NotNull @RequestParam("id") Integer id, HttpServletResponse res,  HttpServletRequest request) throws Exception {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        /**
         * https://admin.lumierecafe.com/wx-api/wx/user/recharge/cancel
         * https://admin.lumierecafe.com/wx-api/wx/user/recharge/success
         */

        String cancelUrl = urlUtils.getBaseURl() + "/" + PAYPAL_CANCEL_URL;
        String successUrl = urlUtils.getBaseURl() + "/" + PAYPAL_SUCCESS_URL;
        /*String cancelUrl = "https://f463283y09.oicp.vip/wx/user/recharge/cancel";
        String successUrl = "https://f463283y09.oicp.vip/wx/user/recharge/success";*/

        Object obj =  wxUserService.getPayment(id, userId, PAYPAL_SUCCESS_URL, PAYPAL_CANCEL_URL);
        if(!(obj instanceof Payment)){
            return obj;
        }
        Payment payment = (Payment)obj;
        for(Links links : payment.getLinks()){
            if(links.getRel().equals("approval_url")){
                res.sendRedirect(links.getHref().toString());
                return "redirect:" + links.getHref();
            }
        }
        return "<script type=\"text/javascript\">location.href=\"/\"</script>" ;
    }

    /**
     * 成功
     *
     * @param paymentId 支付id
     * @param payerId   付款人身份
     * @param resp      分别地
     * @param request   请求
     * @return {@link Object}
     */
    @GetMapping("recharge/success")
    @LogAnno
    public Object success( @NotNull @RequestParam("paymentId") String paymentId, @NotNull @RequestParam("PayerID") String payerId, HttpServletResponse resp, HttpServletRequest request) {

        logger.debug("executePayment");
        Object obj =  wxUserService.executePayment(paymentId, payerId);
        if(!(obj instanceof Payment)){
            return obj;
        }
        Payment payment = (Payment)obj;
        if(payment.getState().equals("approved")){
            //付款完成后生成礼物卡或者更新余额
//            wxUserService.createOrUpdateAmount(paymentId);
//            logger.info(URLUtils.getBaseURl(request));
//            resp.sendRedirect(URLUtils.getBaseURl(request) + "/wx/pay/success");
//            return null;
            return ResponseUtil.ok("success");
        }
        return "<script type=\"text/javascript\">location.href=\"/\"</script>" ;
    }

    /**
     * 取消
     *
     * @return {@link Object}
     */
    @GetMapping("recharge/cancel")
    @LogAnno
    public Object cancel() {
        String html="<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\" />\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n" +
                "    <title>xcLeigh</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            background: #593939;\n" +
                "        }\n" +
                "\n" +
                "        h1 ,h2{\n" +
                "            margin: 100px;\n" +
                "            text-align: center;\n" +
                "            color: white;\n" +
                "            font-family: Arial, Helvetica, sans-serif;\n" +
                "            cursor:pointer;\n" +
                "            font:bold 50px/1.231 ;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "\n" +
                "<body>\n" +
                "<h1 >Cancel successfully</h1>\n" +
                "</body>\n" +
                "\n" +
                "</html>\n" +
                "\n";
        return html;
    }

    /**
     * 历史
     *
     * @param userId 用户id
     * @param page   页面
     * @param limit  限制
     * @param sort   排序
     * @param order  订单
     * @return {@link Object}
     */
    @GetMapping("bill/list")
    @LogAnno
    public Object history(@LoginUser Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @Sort @RequestParam(defaultValue = "add_time") String sort,
            @Order @RequestParam(defaultValue = "desc") String order) {
        if(userId == null){
            return ResponseUtil.unlogin();
        }
        return wxUserService.bill(userId, page, limit, sort, order);
    }




}
